Please explain me the limitation of using ViewBag and how to overcome that limitation in asp.net MVC with example.
What is limitation of using ViewBag and ho we conquer it?
29928-Jan-2020
Updated on 28-Jan-2020
Home / DeveloperSection / Forums / What is limitation of using ViewBag and ho we conquer it?
Please explain me the limitation of using ViewBag and how to overcome that limitation in asp.net MVC with example.
Nishi Tiwari
28-Jan-2020As it’s not suitable for bigger sets of data or more complicated ones. For example, complex relational data, big sets of aggregate data, data coming from a variety of sources, and dashboards.
Also, there are some other potential problems when we are using it. Errors, at some places are not detected during compilation. Because of its dynamic nature, we can create ViewBag names according to our liking. Dynamic properties are not checked during compilation time, unlike normal data types. What does this mean? It means we may not be able to detect if we used the right name and whether it matches the name we specified in the view.
For instance, we have assigned the following properties:
Then use this code for the view:
In this example, we specified Title as a ViewBag name, and this is a valid variable name for the property. But the view is looking for the variable name “Title.” When we compile our program, we would not be alerted to this error.
ViewModel
As discussed above in the limitations section, there are different types of data where we cannot use ViewBag, primarily for those big and complex data sets. For these types of data, we can use ViewModel if we are using ASP.NET MVC.
ViewModel also has a distinct advantage in which it is strongly typed. This means that unlike in ViewBag, ViewModel does not confuse one data type with another data type. For example, using ViewBag, the compiler will not detect an error when we use a DateTime as if it were a string.
ViewBag property using LastIndexOfP in this case, is trying to get ‘p’ based on the PageCreationDate. In this example, we are treating a DateTime as a string, and compiling our program would not detect that error. Using ViewModel, we have better type protection, and error such as this one is detected by the compiler.
The use of ViewBag has some limitations in that the compiler cannot check dynamic types and we would need to run your program first to find the errors when we use it. As such, using ViewModel is highly recommended in some instances.